#include "snake.h"

Snake::Snake(int startX, int startY) : directionX(0), directionY(0), growing(false) {
    body.emplace_back(startX, startY);
}

void Snake::setDirection(int dirX, int dirY) {
    directionX = dirX;
    directionY = dirY;
}

void Snake::move(int dirX, int dirY) {
    // 保存当前头部位置
    std::pair<int, int> newHead = body.front();
    // 使用当前方向移动
    newHead.first += directionX;
    newHead.second += directionY;

    // 在头部插入新位置
    body.insert(body.begin(), newHead);

    // 如果不在生长状态，移除尾部
    if (!growing) {
        body.pop_back();
    } else {
        growing = false;
    }
}

void Snake::grow() {
    growing = true;
}

bool Snake::checkCollision() const {
    auto head = getHead();
    return head.first < 0 || head.first >= 40 || head.second < 0 || head.second >= 30;
}

bool Snake::checkSelfCollision() const {
    auto head = getHead();
    for (size_t i = 1; i < body.size(); ++i) {
        if (body[i] == head) {
            return true;
        }
    }
    return false;
}